package com.autumn.scheduler.job;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;

import com.autumn.mq.IAutumnQueue;
import com.autumn.scheduler.api.QueueJobEventData;
import com.autumn.scheduler.api.constant.ApiConstants.QueueRunState;
import com.autumn.scheduler.domain.entities.AutumnJobLog;
import com.autumn.scheduler.queue.QueueContext;
import com.autumn.util.ExceptionUtils;
import com.autumn.util.StringUtils;

/**
 * 基于 rabbit 的作业
 * 
 * @author 杨昌国 2018-03-19 00:29:43
 */
// 执行完成更新 JobDataMap 中的数据
@PersistJobDataAfterExecution
// 禁止并发执行同一任务
@DisallowConcurrentExecution
public class RabbitJob extends AbstractJob {

	/**
	 * 
	 */
	public RabbitJob() {

	}

	@Override
	protected int executeInternal(JobExecutionContext context, JobExecutionInfo jobInfo, AutumnJobLog jobLog)
			throws JobExecutionException {
		if (!StringUtils.isNullOrBlank(jobInfo.getQueueName())) {
			IAutumnQueue queye = QueueContext.getOrCreateAutumnQueue(jobInfo.getQueueName());
			QueueJobEventData queueJobData = new QueueJobEventData();
			queueJobData.setJobName(jobInfo.getJobFriendlyName());
			queueJobData.setJobGroup(context.getJobDetail().getKey().getGroup());
			queueJobData.setRunNumbers(jobInfo.getRunNumbers());
			queueJobData.setDeleteJob(jobInfo.isDeleteJob());
			queueJobData.setRunTime(jobLog.getRunTime().getTime());
			queueJobData.setSchedTime(jobLog.getSchedTime().getTime());
			queueJobData.setParameterMap(jobInfo.getParameterMap());
			queueJobData.setJobExecuteId(jobLog.getJobExecuteId());
			queye.send(queueJobData, queueJobData.getJobExecuteId());
			return QueueRunState.SEND_SUCCESS;
		} else {
			throw ExceptionUtils.throwApplicationException("队列名称为 null 或空白值，无法推送。");
		}
	}	
}
